package com.dkm.test;

import java.util.List;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

/**
 * 消息接收者
 * @author 狄凯明
 *
 */
public class MQConsumer {

	public static void main(String[] args) throws MQClientException {
		//1.创建消费者consumer，指定消费者组名
		DefaultMQPushConsumer consumer=new DefaultMQPushConsumer("group1");
		//2.指定Nameserver地址
		consumer.setNamesrvAddr("127.0.0.1:9876");
		//3.订阅主题Topic和Tag
		consumer.subscribe("base", "tag1");
		
		//设置消费模式：负载均衡(默认) || 广播模式
		//consumer.setMessageModel(MessageModel.CLUSTERING);//负载均衡(默认)
		consumer.setMessageModel(MessageModel.BROADCASTING);//广播模式
		
		//4.设置回调函数，处理消息
		consumer.registerMessageListener(new MessageListenerConcurrently() {
			
			//接收消息内容
			@Override
			public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
				for (MessageExt msg : msgs) {
					System.out.println(new String(msg.getBody()));
				}
				
				return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
			}
		});
		//5.启动消费者
		consumer.start();
	}
}
